<template>
  <div class="card-content-preview" v-html="sanitizedHtml"></div>
</template>

<script setup lang="ts">
import { computed } from 'vue';

const props = defineProps({
  content: {
    type: String,
    default: ''
  }
});

// 改进的HTML净化，保留基本格式但过滤危险标签和属性
const sanitizedHtml = computed(() => {
  // 如果没有内容直接返回空字符串
  if (!props.content) return '';
  
  // 允许保留的安全标签列表
  const allowedTags = ['p', 'br', 'b', 'i', 'strong', 'em', 'mark', 'small', 'del', 'ins', 'sub', 'sup'];
  
  // 使用DOMParser解析HTML（浏览器内置API）
  const doc = new DOMParser().parseFromString(props.content, 'text/html');
  
  // 递归处理节点
  const sanitizeNode = (node: Node): string => {
    // 文本节点直接返回内容
    if (node.nodeType === Node.TEXT_NODE) {
      return node.textContent || '';
    }
    
    // 非元素节点跳过
    if (node.nodeType !== Node.ELEMENT_NODE) {
      return '';
    }
    
    const element = node as Element;
    const tagName = element.tagName.toLowerCase();
    
    // 如果是允许的标签则保留标签
    if (allowedTags.includes(tagName)) {
      // 收集子节点内容
      let childrenContent = '';
      element.childNodes.forEach(child => {
        childrenContent += sanitizeNode(child);
      });
      
      // 返回带标签的内容
      return `<${tagName}>${childrenContent}</${tagName}>`;
    } else {
      // 不允许的标签只保留内容
      let content = '';
      element.childNodes.forEach(child => {
        content += sanitizeNode(child);
      });
      return content;
    }
  };
  
  // 从body开始处理所有内容
  let sanitized = '';
  doc.body.childNodes.forEach(node => {
    sanitized += sanitizeNode(node);
  });
  
  // 限制最大长度，防止过长内容
  const maxLength = 300;
  if (sanitized.length > maxLength) {
    sanitized = sanitized.substring(0, maxLength) + '...';
  }
  
  return sanitized;
});
</script>

<style scoped>
.card-content-preview {
  height: 4.5em;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 3;
  line-clamp: 3;
  line-height: 1.5em;
  max-height: 4.5em;
  font-size: 14px;
  color: #606266;
}

/* 继承wangeditor的样式但不使用其组件 */
.card-content-preview :deep(p) {
  margin: 0;
  line-height: 1.5em;
}

.card-content-preview :deep(img) {
  max-width: 100%;
}

.card-content-preview :deep(blockquote) {
  border-left: 4px solid #ccc;
  margin: 0;
  padding-left: 10px;
  color: #666;
}

.card-content-preview :deep(pre) {
  background-color: #f1f1f1;
  border-radius: 3px;
  padding: 5px;
  overflow: auto;
}
</style>